<template>
    <div style="margin-top: 20px">
        <a-row>
            <a-col :span="4">
                <div style="background-color: white">
                    <div class="chooseByAreaBox">
                        <span class="chooseByArea">按区域筛选</span>
                    </div>

                    <div class="area-list">
                        <a-tree
                            :blockNode="true"
                            v-if="provinces.length"
                            :default-expand-all="true"
                            :tree-data="provinces"
                            :v-model:checkedKeys="checkedKeys"
                            :v-model:selectedKeys="selectedKeys"
                            @select="onSelect"
                        >
                        </a-tree>
                    </div>
                </div>
            </a-col>
            <a-col :span="20" style="background-color: white;">
                <div class="top" style="height: 50px; padding: 10px 0 ;width: 100%;">
                    <ul class="car-list">
                        <li>
                            <img alt="green car logo" src="@/assets/img/green_car.png" @click="changeStatus(1)">
                            工作
                            <span style="margin-left: 4px;">{{ workMachinesCount }} 辆</span>
                        </li>
                        <li>
                            <img alt="red car logo" src="@/assets/img/gray_car.png" @click="changeStatus(0)">
                            静止
                            <span style="margin-left: 4px;">{{ restMachinesCount }} 辆</span>
                        </li>
                        <li v-if="false">
                            <img alt="gray car logo" src="@/assets/img/red_car.png" @click="changeStatus(2)">
                            离线
                            <span style="margin-left: 4px;">0辆</span>
                        </li>
                        <li>
                            <img alt="yellow car logo" src="@/assets/img/yellow_car.png" @click="changeStatus(3)">
                            强拆
                            <span style="margin-left: 4px;">{{ takeDownMachinesCount }} 辆</span>
                        </li>

                        <a-input-search
                            v-model="input"
                            allow-clear
                            enter-button
                            placeholder="请输入环保编码"
                            style="width: 200px; margin-left: 50px"
                            @search="onSearch"
                        />

                        <a-checkbox v-model="checked" style="margin-left: 6px; line-height: 25px"
                                    @change="()=>{if(checked === false) {mouseTool.close(true);pmValue=null}}">区域颗粒物检测
                        </a-checkbox>

                        <li style="font-size: 14px; font-weight: normal">
                            区域颗粒物平均值：
                            <span v-text="pmValue === null ? '--': pmValue.toFixed(2)"></span>
                            ug/m³
                        </li>

                    </ul>

                </div>

                <a-modal :cancel-button-props="{ style: { display: 'none' } }"
                         :ok-button-props="{ style: { display: 'none' } }"
                         :visible="visible"
                         iconType="question-circle"
                         title="设备位置重复，选择一个设备查看信息"
                         @cancel="visible=false"
                         @ok="visible=false"
                >

                    <a-list :data-source="data" item-layout="horizontal">
                        <a-list-item slot="renderItem" slot-scope="marker" rowKey="id">
                            <a slot="actions" @click="changePointInfo(marker)">查看信息</a>
                            <label for="mec_no">环保编号:
                                <span id="mec_no">{{ marker.getExtData().mec_no }}</span>
                            </label>
                        </a-list-item>
                    </a-list>
                </a-modal>

                <!-- 创建地图的容器 -->
                <div id="container" :style="`height:${height}px`"></div>

                <a-row v-show="checked">
                    <a-col offset="19" span="5">
                        <a-affix :offsetBottom="10">
                            <a-button type="primary" @click="draw('rectangle')">框选区域</a-button>
                            <a-button style="margin-left: 4px" type="danger"
                                      @click="() => {mouseTool.close(true);pmValue=null}">
                                清除绘画
                            </a-button>
                        </a-affix>
                    </a-col>
                </a-row>
            </a-col>
        </a-row>
    </div>
</template>

<script>
// import PageLayout from '@/layouts/PageLayout'
// import HeadInfo from '@/components/tool/HeadInfo'
// import Radar from '@/components/chart/Radar'
import {mapGetters, mapState} from 'vuex'
import {METHOD, request, RESPONSE} from '@/utils/request'
import AMapLoader from '@amap/amap-jsapi-loader';
// eslint-disable-next-line no-unused-vars
import {isChrome} from "ant-design-vue/lib/_util/env";

window._AMapSecurityConfig = {
    securityJsCode: '96fec6c6a41d2f9bd32c423a3c9987dc',
}
export default {

    name: 'WorkPlace',
    // components: {Radar, HeadInfo, PageLayout},
    i18n: require('./i18n'),
    data() {
        return {
            greenImg: require("../../../assets/img/green_site.png"),
            redImg: require("../../../assets/img/red_site.png"),
            yellowImg: require("../../../assets/img/yellow_site.png"),
            flashingImg: require("../../../assets/img/hs.gif"),
            greyImg: require("../../../assets/img/blue_site.png"),
            height: document.body.clientHeight,
            data: [],
            visible: false,
            input: null,
            pointInfo: [],
            bounds: [],
            userID: null,
            checked: false,
            //此处不声明 map 对象，可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
            map: null,
            AMap: null,
            pmValue: null,
            selectedKeys: [],  // 选中的节点
            selectedLevel: null,
            checkedKeys: [],   // 勾选中的节点
            activeKey: 1,
            provinces: [],
            projects: [],
            loading: true,
            activities: [],
            teams: [],
            welcome: {
                timeFix: '',
                message: ''
            },
            staue: null,
            markers: [],
            markersWithSamePos: [],
            currentClickMarker: null, // 当前点击的点对象
            workMachinesCount: 0,
            restMachinesCount: 0,
            takeDownMachinesCount: 0,
            mouseTool: null, // 地图上绘制覆盖物的工具
        }
    },
    computed: {
        ...mapGetters('account', ['user']),
        ...mapState('setting', ['lang'])
    },
    beforeDestroy() {
        // 销毁地图，并清空地图容器
        if (this.map != null) {
            this.map.destroy();
        }
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        //DOM初始化完成进行地图初始化
        this.initMap();

        this.refreshList();

        //写在mounted中,onresize事件会在页面大小被调整时触发
        window.onresize = () => {
            return (() => {
                window.screenHeight = document.body.clientHeight;
                console.log(window.screenHeight);
                this.height = window.screenHeight - 100;
                console.log(this.height);
            })();
        };
    },
    methods: {
        changeStatus(status) {
            this.getRealTimeInfo(status);
        },
        initMarker(marker, item) {

            let pointIndex = item.pm25?.indexOf('.');

            let offset = 0
            // 不同长度的数字设置不同的偏移量
            switch (pointIndex) {
                case undefined:
                    offset = -16;
                    break;
                case 1:
                    offset = -16;
                    break;
                case 2:
                    offset = -20;
                    break;
                case 3:
                    offset = -23;
            }

            marker.setLabel({
                direction: 'right',
                offset: new this.AMap.Pixel(offset, -6),  //设置文本标注偏移量
                content: "<div class='info' style='color:" + item.lableColor + "'>" + (item.pm25 !== null ? item.pm25?.substring(0, pointIndex) : 0) + "</div>", //设置文本标注内容
            });

            var _status = item.status;
            switch (_status) {
                case 0:
                    _status = "<span style='color:green;'>静止</span>";
                    break;
                case 1:
                    _status = "<span style='color:red;'>运动</span>";
                    break;
                case 2:
                    _status = "无信号";
                    break;
                case 3:
                    _status = "<span style='color:#ffb400;'>强拆</span>";
                    break;
            }

            marker.content = "<div style=\"\n" +
                "\t\t\t\t\t\tpadding: 7px;\n" +
                "\t\t\t\t\t\t\"><p>环保编码：" + item
                    .mec_no + " </p><p class=\"\n" +
                "\t\t\t\t\t\tinput - item \">状态：<span style=\"\n" +
                "\t\t\t\t\t\t;\n" +
                "\t\t\t\t\t\t\">" + _status + "</span></p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">电量：" + item
                    .electric + "%</p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">机械类型：" + item
                    .type_name + "</p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">位置：" + item
                    .formatted_address + "</p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">联系人：" + item
                    .contacts + " </p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">电话：" + item.mobile + " </p><p class=\"\n" +
                "\t\t\t\t\t\t input - item \">PM10：" + item
                    .pm25 + "μg/m³</p></div>";


            marker.on('click', this.markerClick);
        },
        getRealTimeInfo(status) {
            request("/mechanics/getDataListByArea", METHOD.GET, {
                id: this.userID,
                sel_level: this.selectedLevel,
                sel_key: this.selectedKeys[0],
                staue: status,
                input: this.input
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.pointInfo = res.data.data;
                    this.$message.success("查询成功");


                    let mapCenter = null;
                    // 找一个在地图中的设备作为显示地图的中心点
                    console.log(`当前区域的编辑长度${this.bounds.length}`)
                    for (var j = 0; j < this.bounds.length; j++) {


                        console.log(`mapCenter${mapCenter}`)
                        console.log(`that.pointInfo${this.pointInfo}`)

                        if (mapCenter == null) {
                            this.pointInfo.forEach((point, index) => {
                                if (mapCenter == null) {
                                    let pointInRing = this.AMap.GeometryUtil.isPointInRing([parseFloat(point.longitude), parseFloat(point.latitude)], this.bounds[j])
                                    console.log(`pointInRing${pointInRing}`)

                                    if (pointInRing) {
                                        console.log(`当前点在区域内${index}`)

                                        // 在区域内部，把它作为显示的中心
                                        mapCenter = [parseFloat(point.longitude), parseFloat(point.latitude)]
                                    } else {
                                        console.log(`当前点不在区域内${index}`)
                                    }
                                }
                            })
                        }
                    }


                    // 清空原来的点
                    this.map.remove(this.markers);
                    // 所有点对象清空
                    this.markers = [];
                    this.markersWithSamePos = [];
                    // 清空统计的车辆数目
                    this.takeDownMachinesCount = 0;
                    this.workMachinesCount = 0;
                    this.restMachinesCount = 0;


                    if (this.pointInfo === null) {
                        this.$message.info("查询结果为空")
                        return;
                    }

                    // 单个点对象
                    var marker;

                    // 创建一个 Marker 实例：
                    for (let i = 0; i < this.pointInfo.length; i++) {
                        let item = this.pointInfo[i];
                        marker = null;

                        // 不同状态的机器点颜色不一样，且统计一下对应的数量
                        let icon;
                        switch (item.status) {
                            case 0:
                                icon = this.greyImg;
                                this.restMachinesCount++;
                                break;
                            case 1:
                                // pm过高 && 并且是工作状态 && 是chrome浏览器
                                console.log('isChrome' + isChrome);
                                if (parseFloat(item.pm25) > 300) {
                                    icon = this.flashingImg;
                                } else if (parseFloat(item.pm25) > 200) {
                                    icon = this.redImg;
                                } else {
                                    icon = this.greenImg;
                                }
                                this.workMachinesCount++;
                                break;
                            case 2:
                                icon = this.yellowImg;
                                this.takeDownMachinesCount++;
                                break;
                            case 3:
                                icon = this.yellowImg;
                                this.takeDownMachinesCount++;
                                break;
                        }
                        // 给每个机械根据pm25一个对应的显示颜色

                        const myColor = ['#00e736', '#ffff1f', '#ff7600', '#ff0000', '#aa0045', '#8d0018'];

                        item.lableColor = "#fff"

                        if (item.pm25 >= 0 && item.pm25 <= 50) {
                            item.color = myColor[0]
                        } else if (item.pm25 <= 100) {
                            item.color = myColor[1]
                        } else if (item.pm25 <= 150) {
                            item.color = myColor[2]
                        } else if (item.pm25 <= 200) {
                            item.color = myColor[3]
                        } else if (item.pm25 <= 300) {
                            item.color = myColor[4]
                            if (item.status === 1) {
                                icon = this.redImg;
                            }
                        } else {
                            item.color = myColor[5]
                            if (item.status === 0) {
                                item.lableColor = "#f00";
                            }
                        }

                        // 处理不能打点的数据
                        if (item.longitude === null || item.latitude === null) {
                            continue;
                        } else {

                            // 能够打点的数据，直接创建marker,在决定这个marker放到二维数组的位置
                            marker = new this.AMap.Marker({
                                // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                                position: [parseFloat(item.longitude), parseFloat(item.latitude)],
                                title: '',
                                icon: icon, // 添加 Icon 图标 URL
                                extData: item
                            });

                            this.initMarker(marker, item);
                            this.markers.push(marker);
                        }

                        // 添加第一个点
                        if (this.markersWithSamePos.length === 0) {
                            // 直接创建一个新的一维数组添加marker
                            let temp = [];
                            temp.push(marker)
                            this.markersWithSamePos.push(temp);
                        } else {
                            // 不是第一个点
                            for (let j = 0; j < this.markersWithSamePos.length; j++) {

                                // 取出二维数组中的第一维
                                let markersWithSamePo = this.markersWithSamePos[j];
                                // 取出一维度数组的第一个
                                let marker1 = markersWithSamePo[0];

                                // console.log(this.markersWithSamePos);
                                // console.log(j);

                                // 高德保存的经纬度为6位小数，四舍五入
                                if (marker1.getPosition().lng.toString() === parseFloat(item.longitude).toFixed(6)
                                    && marker1.getPosition().lat.toString() === parseFloat(item.latitude).toFixed(6)) {
                                    // 和这个数组的第一个元素位置相同，添加到这个数组的末尾
                                    markersWithSamePo.push(marker);

                                    // 有重复的点，旁边的lable只显示一个
                                    // marker.setLabel(null);
                                    console.log("------------------------lable-------------")
                                    console.log(marker.getLabel());

                                    // 找到位置了，就可以处理下一条数据了
                                    break;

                                } else if (j + 1 === this.markersWithSamePos.length) {
                                    // 遍历完成都没有重复位置的点，直接创建一个新的一维数组添加marker
                                    let temp = [];
                                    temp.push(marker)
                                    this.markersWithSamePos.push(temp);

                                    // 上面push导致长度 + 1，不能跳出循环
                                    break;
                                }
                            }
                        }
                    }


                    console.log("屏幕上可以看见的点的个数：" + this.markersWithSamePos.length);

                    // 将创建的点标记添加到已有的地图实例：
                    this.map.add(this.markers);
                    if (this.markers.length > 0 && mapCenter != null) {
                        console.log(this.markers[0].getPosition())
                        this.map.setCenter(mapCenter, true)
                    }

                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        markerClick(e) {
            // 如果没有和当前点击的点位置重复的点，就直接显示信息弹窗
            let currentMarker = e.target;
            this.currentClickMarker = currentMarker;

            for (let i = 0; i < this.markersWithSamePos.length; i++) {
                let markersWithSamePo = this.markersWithSamePos[i];


                if (currentMarker.getPosition().lng === markersWithSamePo[0].getPosition().lng
                    && currentMarker.getPosition().lat === markersWithSamePo[0].getPosition().lat) {
                    if (markersWithSamePo.length === 1) {
                        // 如果没有和当前点击的点位置重复的点，就直接显示信息弹窗
                        var infoWindow = new this.AMap.InfoWindow({
                            offset: new this.AMap.Pixel(0, -30)
                        });

                        infoWindow.setContent(e.target.content);
                        infoWindow.open(this.map, e.target.getPosition());
                    } else {
                        // 有和当前点击的点位置重复的点,显示一个弹窗选择一个点查看信息
                        this.data = markersWithSamePo;

                        console.log(this.data);
                        this.visible = true;
                    }
                }
            }
        },
        refreshList() {
            request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
                if (result.data.code === 1) {
                    this.provinces = result.data.data;
                } else {
                    this.$message = result.data.msg;
                }
            })
        },
        changeActivekey(key) {
            alert(key)
        },
        onSearch() {
            this.getRealTimeInfo();
        },
        initMap() {
            let that = this;
            AMapLoader.load({
                key: "e6ae3ad4789b73879baf6e3a442b7781",             // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.MouseTool', 'AMap.DistrictSearch']      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                that.AMap = AMap;

                var options = {
                    subdistrict: 0,
                    // 返回行政区边界坐标等具体信息
                    extensions: 'all',
                    // 设置查询行政区级别为 区
                    level: 'district'
                };
                const district = new AMap.DistrictSearch(options);


                //查询账号绑定的区域
                district.search(that.user.userqy !== null ? that.user.userqy : '青羊区', function (status, result) {

                    let mask = [];
                    let bounds = [];
                    if (result.districtList === undefined) {
                        this.$message.warn(status);
                    } else {
                        bounds = result.districtList[0]['boundaries'];
                        that.bounds = bounds;
                        for (var i = 0; i < bounds.length; i++) {
                            mask.push([bounds[i]]);
                        }
                    }

                    that.map = new AMap.Map('container', {  //设置地图容器id
                        mask: mask,
                        zoom: 15,                //设置当前显示级别
                        expandZoomRange: true,    //开启显示范围设置
                        zooms: [7, 20],          //最小显示级别为7，最大显示级别为20
                        center: [result.districtList[0].center.lng, result.districtList[0].center.lat], // 显示查询区域的中心
                        viewMode: '2D',          //这里特别注意，设置为3D则其它地区不显示
                        zoomEnable: true,        //是否可以缩放地图
                        resizeEnable: true,
                    });

                    //添加区域描边
                    for (let j = 0; j < bounds.length; j++) {
                        new AMap.Polyline({
                            path: bounds[j],
                            strokeColor: '#3078AC',
                            strokeWeight: 2,
                            map: that.map // 在哪个地图上画线
                        })
                    }

                    that.mouseTool = new AMap.MouseTool(that.map);
                    //监听draw事件可获取画好的覆盖物
                    let lastDrawShape = null;


                    that.mouseTool.on('draw', function (e) {
                        if (lastDrawShape !== null) {
                            that.map.remove(lastDrawShape);
                        }
                        // 最新画的覆盖物
                        lastDrawShape = e.obj;

                        console.log(lastDrawShape);

                        // 判断多少的点在区域里面
                        let sum = 0;
                        let num = 0;
                        that.markers.forEach(marker => {
                            // 使用高德的api判断点在不在多边形内
                            let pointInRing = AMap.GeometryUtil.isPointInRing(marker.getPosition(), lastDrawShape.getPath());
                            if (pointInRing) {
                                sum += parseFloat(marker.getExtData().pm25)
                                num++;
                            }
                        })

                        // 计算覆盖区域内点pm25的平均值
                        that.pmValue = num === 0 ? null : (sum / num);

                        console.log(that.pmValue);
                    })


                    that.getRealTimeInfo();
                });
            }).catch(e => {
                console.log(e);
            })
        },
        // 点击选择了一个区域
        onSelect(selectedKeys, info) {
            console.log(selectedKeys);
            this.selectedKeys = selectedKeys;
            console.log('onSelect', info);
            this.onShowSizeChange()
        },
        findAreaByKey(area, key) {

            if (area.children != null && area.children.length > 0) {
                // 有子节点查询所有的子节点
                for (let i = 0; i < area.children.length; i++) {
                    let result = this.findAreaByKey(area.children[i], key);
                    if (result != null) {
                        // 找到了直接返回结果
                        return result;
                    }
                }
            }

            // 没有子节点 或者子节点查完了，检查本身节点
            if (area.key === key) {
                // 找到了直接返回结果
                return area;
            } else {
                // 告诉父节点没找到，继续找
                return null;
            }

        },
        onShowSizeChange() {
            let area = null;
            // 查找当前选中的层级
            if (this.selectedKeys.length !== 0) {
                // 左侧区域选中了层级就查询这个层级的设备
                for (let i = 0; i < this.provinces.length; i++) {
                    area = this.findAreaByKey(this.provinces[i], this.selectedKeys[0]);
                    if (area != null) {
                        // 找到了就发送请求结束
                        this.selectedLevel = area.level;
                        this.getRealTimeInfo();
                        return;
                    }
                }

                this.selectedLevel = null;
            } else {
                // 左侧区域没选择就查询所有的设备
                this.selectedLevel = null;
                this.getRealTimeInfo();
            }
        },
        changePointInfo(marker) {
            // 显示点的信息
            var infoWindow = new this.AMap.InfoWindow({
                offset: new this.AMap.Pixel(0, -30)
            });

            infoWindow.setContent(marker.content);
            infoWindow.open(this.map, marker.getPosition());

            let item = marker.getExtData();

            // 小数点的位置
            let pointIndex = item.pm25?.indexOf('.');
            // 点上显示的数字

            let offset = 0
            // 不同长度的数字设置不同的偏移量
            switch (pointIndex) {
                case 1:
                    offset = -16;
                    break;
                case 2:
                    offset = -20;
                    break;
                case 3:
                    offset = -23;
            }

            // 旁边所有的标签不显示了
            this.data.forEach(temp => {
                temp.setLabel({
                    direction: 'right',
                    offset: new this.AMap.Pixel(offset, -6),  //设置文本标注偏移量
                    content: "<div class='info' style='color:" + item.lableColor + "'>" + (item.pm25 !== null ? item.pm25?.substring(0, pointIndex) : 0) + "</div>", //设置文本标注内容
                });
            })


            // 隐藏弹窗
            this.visible = false;
        },
        draw(type) {
            switch (type) {
                case 'marker': {
                    this.mouseTool.marker({
                        //同Marker的Option设置
                    });
                    break;
                }
                case 'polyline': {
                    this.mouseTool.polyline({
                        strokeColor: '#80d8ff'
                        //同Polyline的Option设置
                    });
                    break;
                }
                case 'polygon': {
                    this.mouseTool.polygon({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Polygon的Option设置
                    });
                    break;
                }
                case 'rectangle': {
                    this.mouseTool.rectangle({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Polygon的Option设置
                    });
                    break;
                }
                case 'circle': {
                    this.mouseTool.circle({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Circle的Option设置
                    });
                    break;
                }
            }
        }

    }
}
</script>

<style lang="less" scoped>
@import '../../../../src/assets/css/index.css';

/deep/ .ant-tree-title {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2; //在第几行显示...
}

#container {
    padding: 0;
    margin: 0;
    width: 100%;
    height: inherit;
}

img {
    width: 25px;
    height: 25px;
    cursor: pointer;
}

.chooseByArea {
    font-weight: 600;
    color: #1890ff;
    font-size: 14px;
    cursor: pointer;
    margin-left: 6px;
}

.chooseByAreaBox {
    border: 6px !important;
    border-bottom-color: blue;
    padding: 12px 0;
}

.area-list {
    width: 100%;
    height: 500px;
}


//列表横着放
.car-list li {
    display: inline;
    margin-left: 8px;
}

.car-list {
    overflow: hidden;
    font-size: 16px;
    font-weight: 500;
    padding: 0;
    margin: 0;
    list-style: none;
}
</style>
